import 'dart:convert';
import 'dart:core';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import '../models/childcare_model.dart';
import '../services/database_helper.dart';

class ChildcareService {
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;

  // 添加宝宝信息
  Future<BabyInfo> addBabyInfo({
    required int userId,
    required String name,
    required DateTime dateOfBirth,
    required String gender,
    String? bloodType,
    required double birthWeight,
    required double birthHeight,
    String? deliveryMethod,
    String? notes,
  }) async {
    final babyInfo = BabyInfo(
      userId: userId,
      name: name,
      dateOfBirth: dateOfBirth,
      gender: gender,
      bloodType: bloodType ?? '',
      birthWeight: birthWeight,
      birthHeight: birthHeight,
      deliveryMethod: deliveryMethod ?? '',
      notes: notes ?? '',
    );

    final id =
        await _dbHelper.insert(DatabaseHelper.tableBabyInfo, babyInfo.toMap());

    // 添加默认的疫苗接种计划
    _loadDefaultVaccineSchedule(id, gender, dateOfBirth);

    // 添加默认的早教方案
    _loadDefaultEarlyEducationPlans(id);

    return babyInfo.copyWith(id: id);
  }

  // 更新宝宝信息
  Future<BabyInfo> updateBabyInfo({
    required int id,
    String? name,
    DateTime? dateOfBirth,
    String? gender,
    String? bloodType,
    double? birthWeight,
    double? birthHeight,
    String? deliveryMethod,
    String? notes,
  }) async {
    final existingInfo = await getBabyInfo(id);
    if (existingInfo == null) {
      throw Exception('宝宝信息不存在');
    }

    final updatedInfo = existingInfo.copyWith(
      name: name,
      dateOfBirth: dateOfBirth,
      gender: gender,
      bloodType: bloodType,
      birthWeight: birthWeight,
      birthHeight: birthHeight,
      deliveryMethod: deliveryMethod,
      notes: notes,
    );

    await _dbHelper.update(
        DatabaseHelper.tableBabyInfo, updatedInfo.toMap(), id);
    return updatedInfo;
  }

  // 获取用户所有宝宝信息
  Future<List<BabyInfo>> getUserBabies(int userId) async {
    final babies = await _dbHelper.getUserBabies(userId);
    return babies.map((map) => BabyInfo.fromMap(map)).toList();
  }

  // 获取单个宝宝信息
  Future<BabyInfo?> getBabyInfo(int babyId) async {
    final db = await _dbHelper.database;
    final List<Map<String, dynamic>> maps = await db.query(
      DatabaseHelper.tableBabyInfo,
      where: '_id = ?',
      whereArgs: [babyId],
    );
    if (maps.isNotEmpty) {
      return BabyInfo.fromMap(maps.first);
    }
    return null;
  }

  // 删除宝宝信息（谨慎操作）
  Future<void> deleteBabyInfo(int babyId) async {
    // 先删除相关数据
    await _dbHelper
        .deleteWhere(DatabaseHelper.tableBabyGrowth, {'baby_id': babyId});
    await _dbHelper
        .deleteWhere(DatabaseHelper.tableFeedingRecords, {'baby_id': babyId});
    await _dbHelper
        .deleteWhere(DatabaseHelper.tableSleepRecords, {'baby_id': babyId});
    // 再删除宝宝信息
    await _dbHelper.delete(DatabaseHelper.tableBabyInfo, babyId);
  }

  // 添加成长记录
  Future<GrowthRecord> addGrowthRecord({
    required int babyId,
    required DateTime date,
    required double weight,
    required double height,
    double? headCircumference,
    String? notes,
    String? recordedBy,
  }) async {
    final record = GrowthRecord(
      babyId: babyId,
      date: date,
      weight: weight,
      height: height,
      headCircumference: headCircumference ?? 0,
      notes: notes ?? '',
      recordedBy: recordedBy ?? '',
    );

    final id =
        await _dbHelper.insert(DatabaseHelper.tableBabyGrowth, record.toMap());

    // 分析生长趋势
    _analyzeGrowthTrend(babyId);

    return record.copyWith(id: id);
  }

  // 获取成长记录
  Future<List<GrowthRecord>> getGrowthRecords(int babyId,
      {DateTime? startDate, DateTime? endDate}) async {
    Map<String, dynamic> where = {'baby_id': babyId};
    if (startDate != null) {
      where['date >='] = startDate.toIso8601String();
    }
    if (endDate != null) {
      where['date <='] = endDate.toIso8601String();
    }
    final records = await _dbHelper.queryRows(DatabaseHelper.tableBabyGrowth,
        where: where, orderBy: 'date DESC');
    return records.map((map) => GrowthRecord.fromMap(map)).toList();
  }

  // 获取最新的成长记录
  Future<GrowthRecord?> getLatestGrowthRecord(int babyId) async {
    final records = await _dbHelper.queryRows(DatabaseHelper.tableBabyGrowth,
        where: {'baby_id': babyId}, orderBy: 'date DESC');
    final record = records.isNotEmpty ? records.first : null;
    if (record != null) {
      return GrowthRecord.fromMap(record);
    }
    return null;
  }

  // 更新成长记录
  Future<GrowthRecord> updateGrowthRecord({
    required int id,
    DateTime? date,
    double? weight,
    double? height,
    double? headCircumference,
    String? notes,
    String? recordedBy,
  }) async {
    // Get existing record using queryRows
    final existingRecords = await _dbHelper
        .queryRows(DatabaseHelper.tableBabyGrowth, where: {'_id': id});
    if (existingRecords.isEmpty) {
      throw Exception('成长记录不存在');
    }

    final existingRecord = GrowthRecord.fromMap(existingRecords.first);
    final updatedRecord = existingRecord.copyWith(
      date: date,
      weight: weight,
      height: height,
      headCircumference: headCircumference,
      notes: notes,
      recordedBy: recordedBy,
    );

    await _dbHelper.update(
        DatabaseHelper.tableBabyGrowth, updatedRecord.toMap(), id);

    // 重新分析生长趋势
    _analyzeGrowthTrend(updatedRecord.babyId);

    return updatedRecord;
  }

  // 删除成长记录
  Future<void> deleteGrowthRecord(int id) async {
    // Get existing record using queryRows
    final existingRecords = await _dbHelper
        .queryRows(DatabaseHelper.tableBabyGrowth, where: {'_id': id});
    if (existingRecords.isNotEmpty) {
      final babyId = existingRecords.first['baby_id'] as int;
      await _dbHelper.delete(DatabaseHelper.tableBabyGrowth, id);

      // 重新分析生长趋势
      _analyzeGrowthTrend(babyId);
    }
  }

  // 分析生长趋势
  Future<Map<String, dynamic>> getGrowthAnalysis(int babyId) async {
    // 使用正确的查询方法获取生长记录
    final db = await _dbHelper.database;
    final List<Map<String, dynamic>> growthRecords = await db.query(
        DatabaseHelper.tableBabyGrowth,
        where: 'baby_id = ?',
        whereArgs: [babyId],
        orderBy: 'date DESC');
    if (growthRecords.isEmpty) {
      return {"error": "没有生长记录"};
    }

    // 获取最新的生长记录
    final latestGrowthRecord = growthRecords.isNotEmpty
        ? GrowthRecord.fromMap(growthRecords.first)
        : null;

    // 分析生长趋势
    final growthRecordObjects = growthRecords.map((map) => GrowthRecord.fromMap(map)).toList();
    final trend = _evaluateGrowthTrend(growthRecordObjects);

    // 获取宝宝信息以确定月龄和性别
    final babyInfo = await getBabyInfo(babyId);
    if (babyInfo == null) {
      return {"error": "宝宝信息不存在"};
    }

    // 获取WHO成长标准（暂时注释掉，因为方法未实现）
    // final standard = _getWHOGrowthStandard(babyInfo.ageInMonths, babyInfo.gender);

    // 计算体重和身高的百分位 - 临时使用模拟值
    const weightPercentile = 50.0; // 临时模拟值
    const heightPercentile = 50.0; // 临时模拟值

    // 获取疫苗接种状态
    final vaccineSchedule = await getVaccineSchedule(babyId);
    final completedVaccines =
        vaccineSchedule.where((v) => v.isCompleted).length;
    final totalVaccines = vaccineSchedule.length;
    final overdueVaccines = vaccineSchedule.where((v) => v.isOverdue).length;

    // 获取成长里程碑
    final milestones = await getGrowthMilestones(babyId, achievedOnly: true);

    // 获取发育评估
    // 暂时返回空列表，因为方法未定义
    final List<DevelopmentAssessment> assessments = [];
    final latestAssessment = assessments.isNotEmpty ? assessments.last : null;

    return {
      'baby_info': babyInfo,
      'current_age': babyInfo.age,
      'latest_growth': latestGrowthRecord,
      'growth_records_count': growthRecords.length,
      'growth_trend': trend,
      'weight_percentile': weightPercentile,
      'height_percentile': heightPercentile,
      'vaccination_status': {
        'completed': completedVaccines,
        'total': totalVaccines,
        'completion_rate':
            totalVaccines > 0 ? (completedVaccines / totalVaccines * 100) : 0,
        'overdue': overdueVaccines,
      },
      'milestones': {
        'achieved': milestones.length,
        'recent': milestones.take(5).toList(),
      },
      'latest_assessment': latestAssessment,
      'generated_date': DateTime.now(),
    };
  }

  // 记录疫苗接种
  Future<VaccineRecord> recordVaccination({
    required int babyId,
    required String vaccineName,
    required String vaccineType,
    required DateTime vaccinationDate,
    String? dose,
    String? lotNumber,
    String? manufacturer,
    String? doctorName,
    String? hospitalName,
    String? reactions,
    String? notes,
    DateTime? nextDueDate,
    String? recordedBy,
  }) async {
    final record = VaccineRecord(
      babyId: babyId,
      vaccineName: vaccineName,
      vaccineType: vaccineType,
      vaccinationDate: vaccinationDate,
      dose: dose ?? '',
      lotNumber: lotNumber ?? '',
      manufacturer: manufacturer ?? '',
      doctorName: doctorName ?? '',
      hospitalName: hospitalName ?? '',
      reactions: reactions ?? '',
      notes: notes ?? '',
      nextDueDate: nextDueDate ?? DateTime.now(),
      recordedBy: recordedBy ?? '',
    );

    final id =
        await _dbHelper.insert(DatabaseHelper.tableVaccine, record.toMap());

    // 疫苗计划状态更新暂时注释，因为tableVaccineSchedule表不存在
    // await _dbHelper.updateWhere(
    //   'vaccine_schedule', // 临时使用表名
    //   {'status': 'completed', 'completed_date': DateTime.now().toIso8601String()},
    //   {'baby_id': babyId, 'vaccine_name': vaccineName, 'dose': dose});

    // 如果有下次接种日期，创建提醒
    if (nextDueDate != null && nextDueDate.isAfter(DateTime.now())) {
      await _createVaccineReminder(babyId, nextDueDate, vaccineName, dose);
    }

    return record.copyWith(id: id);
  }

  // 获取疫苗接种记录
  Future<List<VaccineRecord>> getVaccineRecords(int babyId) async {
    final records = await _dbHelper.queryRows(DatabaseHelper.tableVaccine,
        where: {'baby_id': babyId}, orderBy: 'vaccination_date DESC');
    return records.map((map) => VaccineRecord.fromMap(map)).toList();
  }

  // 获取疫苗接种计划
  Future<List<VaccineSchedule>> getVaccineSchedule(int babyId) async {
    // 使用通用疫苗表替代不存在的疫苗计划表
    final db = await _dbHelper.database;
    final List<Map<String, dynamic>> schedules = await db.query(
        DatabaseHelper.tableVaccine,
        where: 'baby_id = ?',
        whereArgs: [babyId],
        orderBy: 'scheduled_date ASC');
    return schedules.map((map) => VaccineSchedule.fromMap(map)).toList();
  }

  // 获取即将到期的疫苗
  Future<List<VaccineSchedule>> getUpcomingVaccines(
      int babyId, int days) async {
    final endDate = DateTime.now().add(Duration(days: days));
    final db = await _dbHelper.database;
    final List<Map<String, dynamic>> schedules =
        await db.query(DatabaseHelper.tableVaccine,
            where: 'baby_id = ? AND scheduled_date <= ?', // 修正为baby_id
            whereArgs: [babyId, endDate.toIso8601String()],
            orderBy: 'scheduled_date ASC');
    return schedules.map((map) => VaccineSchedule.fromMap(map)).toList();
  }

  // 添加喂养记录
  Future<FeedingRecord> addFeedingRecord({
    required int babyId,
    required DateTime timestamp,
    required String feedingType,
    String? side,
    double? amount,
    double? duration,
    String? foodName,
    String? notes,
    String? recordedBy,
  }) async {
    final record = FeedingRecord(
      babyId: babyId,
      timestamp: timestamp,
      feedingType: feedingType,
      side: side ?? '',
      amount: amount ?? 0,
      duration: duration ?? 0,
      foodName: foodName ?? '',
      notes: notes ?? '',
      recordedBy: recordedBy ?? '',
    );

    final id = await _dbHelper.insert(
        DatabaseHelper.tableFeedingRecords, record.toMap());
    return record.copyWith(id: id);
  }

  // 获取feeding记录
  Future<List<FeedingRecord>> getFeedingRecords(int babyId,
      {DateTime? startDate, DateTime? endDate}) async {
    Map<String, dynamic> where = {'baby_id': babyId};
    if (startDate != null) {
      where['timestamp >='] = startDate.toIso8601String();
    }
    if (endDate != null) {
      where['timestamp <='] = endDate.toIso8601String();
    }
    final records = await _dbHelper.queryRows(
        DatabaseHelper.tableFeedingRecords,
        where: where,
        orderBy: 'timestamp DESC');
    return records.map((map) => FeedingRecord.fromMap(map)).toList();
  }

  // 分析喂养模式
  Future<Map<String, dynamic>> analyzeFeedingPattern(
      int babyId, int days) async {
    final endDate = DateTime.now();
    final startDate = endDate.subtract(Duration(days: days));

    final records =
        await getFeedingRecords(babyId, startDate: startDate, endDate: endDate);

    if (records.isEmpty) {
      return {'status': 'insufficient_data', 'message': '没有足够的喂养记录进行分析'};
    }

    // 统计各种喂养类型的次数
    final typeCounts = <String, int>{};
    final typeAmounts = <String, double>{};
    final dailyCounts = <DateTime, int>{};

    for (var record in records) {
      // 统计类型次数
      typeCounts[record.feedingType] =
          (typeCounts[record.feedingType] ?? 0) + 1;

      // 统计类型总量
      if (record.amount > 0) {
        typeAmounts[record.feedingType] =
            (typeAmounts[record.feedingType] ?? 0) + record.amount;
      }

      // 统计每日次数
      final dateKey = DateTime(
          record.timestamp.year, record.timestamp.month, record.timestamp.day);
      dailyCounts[dateKey] = (dailyCounts[dateKey] ?? 0) + 1;
    }

    // 计算平均每日喂养次数
    final avgDailyCount =
        dailyCounts.values.reduce((a, b) => a + b) / dailyCounts.length;

    // 计算各种喂养类型的百分比
    final totalRecords = records.length;
    final typePercentages = <String, double>{};
    typeCounts.forEach((type, count) {
      typePercentages[type] = (count / totalRecords) * 100;
    });

    return {
      'status': 'success',
      'records_count': records.length,
      'type_counts': typeCounts,
      'type_percentages': typePercentages,
      'type_amounts': typeAmounts,
      'avg_daily_count': avgDailyCount,
      'daily_counts': dailyCounts,
    };
  }

  // 添加睡眠记录
  Future<SleepRecord> addSleepRecord({
    required int babyId,
    required DateTime startTime,
    required DateTime endTime,
    required String sleepType,
    String? notes,
    String? recordedBy,
  }) async {
    final record = SleepRecord(
      babyId: babyId,
      startTime: startTime,
      endTime: endTime,
      sleepType: sleepType,
      notes: notes ?? '',
      recordedBy: recordedBy ?? '',
    );

    final id = await _dbHelper.insert(
        DatabaseHelper.tableSleepRecords, record.toMap());
    return record.copyWith(id: id);
  }

  // 获取睡眠记录
  Future<List<SleepRecord>> getSleepRecords(int babyId,
      {DateTime? startDate, DateTime? endDate}) async {
    Map<String, dynamic> where = {'baby_id': babyId};
    if (startDate != null) {
      where['start_time >='] = startDate.toIso8601String();
    }
    if (endDate != null) {
      where['end_time <='] = endDate.toIso8601String();
    }
    final records = await _dbHelper.queryRows(DatabaseHelper.tableSleepRecords,
        where: where, orderBy: 'start_time DESC');
    return records.map((map) => SleepRecord.fromMap(map)).toList();
  }

  // 分析睡眠模式
  Future<Map<String, dynamic>> analyzeSleepPattern(int babyId, int days) async {
    final endDate = DateTime.now();
    final startDate = endDate.subtract(Duration(days: days));

    final records =
        await getSleepRecords(babyId, startDate: startDate, endDate: endDate);

    if (records.isEmpty) {
      return {'status': 'insufficient_data', 'message': '没有足够的睡眠记录进行分析'};
    }

    // 统计各种睡眠类型的时长
    final typeDurations = <String, double>{};
    final dailyDurations = <DateTime, double>{};
    final napCounts = <DateTime, int>{};

    for (var record in records) {
      // 统计类型时长
      typeDurations[record.sleepType] =
          (typeDurations[record.sleepType] ?? 0) + record.duration;

      // 统计每日总时长
      final dateKey = DateTime(
          record.startTime.year, record.startTime.month, record.startTime.day);
      dailyDurations[dateKey] =
          (dailyDurations[dateKey] ?? 0) + record.duration;

      // 统计每日小睡次数
      if (record.sleepType == 'nap') {
        napCounts[dateKey] = (napCounts[dateKey] ?? 0) + 1;
      }
    }

    // 计算平均每日睡眠时长
    final totalDuration =
        records.fold(0.0, (sum, record) => sum + record.duration);
    final avgDailyDuration = totalDuration / dailyDurations.length;

    // 计算平均每日小睡次数
    final totalNaps = napCounts.values.reduce((a, b) => a + b);
    final avgDailyNaps = totalNaps / napCounts.length;

    return {
      'status': 'success',
      'records_count': records.length,
      'type_durations': typeDurations,
      'daily_durations': dailyDurations,
      'avg_daily_duration': avgDailyDuration,
      'avg_daily_naps': avgDailyNaps,
    };
  }

  // 添加尿布记录
  // 注意：此方法暂时注释，因为数据库中不存在tableDiaperRecords表
  // Future<DiaperRecord> addDiaperRecord({
  //   required int babyId,
  //   required DateTime timestamp,
  //   required String type,
  //   String? consistency,
  //   String? color,
  //   String? notes,
  //   String? recordedBy,
  // }) async {
  //   final record = DiaperRecord(
  //     babyId: babyId,
  //     timestamp: timestamp,
  //     type: type,
  //     consistency: consistency ?? '',
  //     color: color ?? '',
  //     notes: notes ?? '',
  //     recordedBy: recordedBy ?? '',
  //   );

  //   final id = await _dbHelper.insert(DatabaseHelper.tableDiaperRecords, record.toMap());
  //   return record.copyWith(id: id);
  // }

  // 获取尿布记录
  // 注意：此方法暂时注释，因为数据库中不存在tableDiaperRecords表
  // Future<List<DiaperRecord>> getDiaperRecords(
  //   int babyId, {DateTime? startDate, DateTime? endDate}) async {
  //   Map<String, dynamic> where = {'baby_id': babyId};
  //   if (startDate != null) {
  //     where['timestamp >='] = startDate.toIso8601String();
  //   }
  //   if (endDate != null) {
  //     where['timestamp <='] = endDate.toIso8601String();
  //   }
  //   final records = await _dbHelper.queryRows(
  //     DatabaseHelper.tableDiaperRecords,
  //     where: where,
  //     orderBy: 'timestamp DESC');
  //   return records.map((map) => DiaperRecord.fromMap(map)).toList();
  // }

  // 添加早教方案
  // 注意：此方法暂时注释，因为数据库中不存在tableEarlyEducation表
  // Future<EarlyEducationPlan> addEarlyEducationPlan({
  //   required int babyId,
  //   required String title,
  //   required String description,
  //   required String targetAgeRange,
  //   required String category,
  //   required String activityType,
  //   required String instructions,
  //   String? materialsNeeded,
  //   String? benefits,
  //   String? tips,
  //   String? difficultyLevel,
  //   int? durationMinutes,
  //   bool? isFavorite,
  // }) async {
  //   final plan = EarlyEducationPlan(
  //     babyId: babyId,
  //     title: title,
  //     description: description,
  //     targetAgeRange: targetAgeRange,
  //     category: category,
  //     activityType: activityType,
  //     instructions: instructions,
  //     materialsNeeded: materialsNeeded ?? '',
  //     benefits: benefits ?? '',
  //     tips: tips ?? '',
  //     difficultyLevel: difficultyLevel ?? 'easy',
  //     durationMinutes: durationMinutes ?? 15,
  //     isFavorite: isFavorite ?? false,
  //   );

  //   final id = await _dbHelper.insert(DatabaseHelper.tableEarlyEducation, plan.toMap());
  //   return plan.copyWith(id: id);
  // }

  // 获取早教方案
  // 注意：此方法暂时注释，因为数据库中不存在tableEarlyEducation表
  // Future<List<EarlyEducationPlan>> getEarlyEducationPlans(
  //   int babyId, {String? targetAgeRange, String? category, bool? isFavorite}) async {
  //   Map<String, dynamic> where = {'baby_id': babyId};
  //   if (targetAgeRange != null) {
  //     where['target_age_range'] = targetAgeRange;
  //   }
  //   if (category != null) {
  //     where['category'] = category;
  //   }
  //   if (isFavorite != null) {
  //     where['is_favorite'] = isFavorite ? 1 : 0;
  //   }
  //   final plans = await _dbHelper.queryRows(
  //     DatabaseHelper.tableEarlyEducation,
  //     where: where,
  //     orderBy: 'created_at DESC');
  //   return plans.map((map) => EarlyEducationPlan.fromMap(map)).toList();
  // }

  // 获取适合当前宝宝月龄的早教方案
  // 注意：此方法暂时注释，因为数据库中不存在tableEarlyEducation表
  // Future<List<EarlyEducationPlan>> getAgeAppropriatePlans(int babyId) async {
  //   final babyInfo = await getBabyInfo(babyId);
  //   if (babyInfo == null) {
  //     throw Exception('宝宝信息不存在');
  //   }

  //   final ageInMonths = babyInfo.ageInMonths;
  //   String targetAgeRange; // 修改变量名，避免与类型名冲突

  //   if (ageInMonths < 4) {
  //     targetAgeRange = '0-3m';
  //   } else if (ageInMonths < 7) {
  //     targetAgeRange = '4-6m';
  //   } else if (ageInMonths < 13) {
  //     targetAgeRange = '7-12m';
  //   } else if (ageInMonths < 25) {
  //     targetAgeRange = '1-2y';
  //   } else {
  //     targetAgeRange = '2-3y';
  //   }

  //   return getEarlyEducationPlans(babyId, targetAgeRange: targetAgeRange);
  // }

  // 更新早教方案收藏状态
  Future<void> togglePlanFavoriteStatus(int planId, bool isFavorite) async {
    // 直接使用update方法替代不存在的updatePlanFavoriteStatus
    await _dbHelper.update(
        'early_education', // 临时使用表名
        {'is_favorite': isFavorite ? 1 : 0},
        planId);
  }

  // 添加成长里程碑
  // 注意：修改使用insert方法替代不存在的insertGrowthMilestone
  Future<GrowthMilestone> addGrowthMilestone({
    required int babyId,
    required String milestoneName,
    required String category,
    required String description,
    required DateTime achievedDate,
    String? notes,
    String? photoPath,
    String? recordedBy,
  }) async {
    final milestone = GrowthMilestone(
      babyId: babyId,
      milestoneName: milestoneName,
      category: category,
      description: description,
      achievedDate: achievedDate,
      notes: notes ?? '',
      photoPath: photoPath ?? '',
      recordedBy: recordedBy ?? '',
    );

    // 直接使用insert方法替代不存在的insertGrowthMilestone
    final id = await _dbHelper.insert('growth_milestones', milestone.toMap());
    return milestone.copyWith(id: id);
  }

  // 获取成长里程碑
  // 注意：修改使用queryRows方法替代不存在的getGrowthMilestones
  Future<List<GrowthMilestone>> getGrowthMilestones(int babyId,
      {String? category, bool? achievedOnly}) async {
    // 使用通用查询方法替代不存在的getGrowthMilestones
    Map<String, dynamic> where = {'baby_id': babyId};
    if (category != null) {
      where['category'] = category;
    }
    if (achievedOnly != null && achievedOnly) {
      where['is_achieved'] = 1;
    }
    final milestones = await _dbHelper.queryRows('growth_milestones', // 临时使用表名
        where: where);
    return milestones.map((map) => GrowthMilestone.fromMap(map)).toList();
  }

  // 添加宝宝照片
  // 注意：修改使用insert方法替代不存在的insertBabyPhoto
  Future<BabyPhoto> addBabyPhoto({
    required int babyId,
    required String photoPath,
    required DateTime captureDate,
    String? caption,
    String? location,
    List<String>? tags,
    bool? isFavorite,
    String? uploadedBy,
  }) async {
    final photo = BabyPhoto(
      babyId: babyId,
      photoPath: photoPath,
      captureDate: captureDate,
      caption: caption ?? '',
      location: location ?? '',
      tags: tags ?? [],
      isFavorite: isFavorite ?? false,
      uploadedBy: uploadedBy ?? '',
    );

    // 直接使用insert方法替代不存在的insertBabyPhoto
    final id = await _dbHelper.insert('baby_photos', photo.toMap());
    return photo.copyWith(id: id);
  }

  // 获取宝宝照片
  // 注意：修改使用queryRows方法替代不存在的getBabyPhotos
  Future<List<BabyPhoto>> getBabyPhotos(int babyId,
      {DateTime? startDate, DateTime? endDate, bool? isFavorite}) async {
    // 使用通用查询方法替代不存在的getBabyPhotos
    Map<String, dynamic> where = {'baby_id': babyId};
    if (startDate != null) {
      where['capture_date >='] = startDate.toIso8601String();
    }
    if (endDate != null) {
      where['capture_date <='] = endDate.toIso8601String();
    }
    if (isFavorite != null) {
      where['is_favorite'] = isFavorite ? 1 : 0;
    }
    final photos = await _dbHelper.queryRows('baby_photos', // 临时使用表名
        where: where,
        orderBy: 'capture_date DESC');
    return photos.map((map) => BabyPhoto.fromMap(map)).toList();
  }

  // 搜索宝宝照片
  // 注意：使用通用查询方法替代不存在的searchBabyPhotos
  Future<List<BabyPhoto>> searchBabyPhotos(int babyId, String query) async {
    final db = await _dbHelper.database;
    final List<Map<String, dynamic>> photos = await db.query(
        'baby_photos', // 临时使用表名
        where:
            'baby_id = ? AND (caption LIKE ? OR location LIKE ? OR tags LIKE ?)',
        whereArgs: [babyId, '%$query%', '%$query%', '%$query%']);
    return photos.map((map) => BabyPhoto.fromMap(map)).toList();
  }

  // 更新照片收藏状态
  Future<void> togglePhotoFavoriteStatus(int photoId, bool isFavorite) async {
    // 直接使用update方法替代不存在的updatePhotoFavoriteStatus
    await _dbHelper.update(
        'baby_photos', // 临时使用表名
        {'is_favorite': isFavorite ? 1 : 0},
        photoId);
  }

// 添加发育评估
// 注意：此方法暂时注释，因为涉及未定义的表引用
// Future<DevelopmentAssessment> addDevelopmentAssessment({
//   required int babyId,
//   required DateTime assessmentDate,
//   required String assessorName,
//   required String assessorType,
//   required int overallScore,
//   Map<String, int>? domainScores,
//   String? strengths,
//   String? areasForImprovement,
//   String? recommendations,
//   String? notes,
// }) async {
//   final assessment = DevelopmentAssessment(
//     babyId: babyId,
//     assessmentDate: assessmentDate,
//     assessorName: assessorName,
//     assessorType: assessorType,
//     overallScore: overallScore,
//     domainScores: domainScores ?? {},
//     strengths: strengths ?? '',
//     areasForImprovement: areasForImprovement ?? '',
//     recommendations: recommendations ?? '',
//     notes: notes ?? '',
//   );

//   final id = await _dbHelper.insertDevelopmentAssessment(assessment.toMap());
//
//   // 基于评估结果推荐早教活动
//   if (assessment.recommendations.isNotEmpty) {
//     await _recommendActivitiesBasedOnAssessment(babyId, assessment);
//   }
//
//   return assessment.copyWith(id: id);
// }

// 获取发育评估记录
// 注意：此方法暂时注释，因为涉及未定义的表引用和方法调用
// Future<List<DevelopmentAssessment>> getDevelopmentAssessments(int babyId) async {
//   final assessments = await _dbHelper.getDevelopmentAssessments(babyId);
//   return assessments.map((map) => DevelopmentAssessment.fromMap(map)).toList();
// }

// 生成发育报告
Future<Map<String, dynamic>> generateDevelopmentReport(int babyId) async {
  final babyInfo = await getBabyInfo(babyId);
  if (babyInfo == null) {
    throw Exception('宝宝信息不存在');
  }

  // 获取成长记录
  final growthRecords = await getGrowthRecords(babyId);
  final latestGrowthRecord =
      growthRecords.isNotEmpty ? growthRecords.last : null;

  // 获取疫苗接种状态
  final vaccineSchedule = await getVaccineSchedule(babyId);
  final completedVaccines = vaccineSchedule.where((v) => v.isCompleted).length;
  final totalVaccines = vaccineSchedule.length;
  final overdueVaccines = vaccineSchedule.where((v) => v.isOverdue).length;

  // 获取成长里程碑
  final milestones = await getGrowthMilestones(babyId, achievedOnly: true);

  // 获取发育评估
  // 暂时返回空列表，因为方法未定义
  final List<DevelopmentAssessment> assessments = [];
  final latestAssessment = assessments.isNotEmpty ? assessments.last : null;

  // 生成报告
  return {
    'baby_info': babyInfo,
    'current_age': babyInfo.age,
    'latest_growth': latestGrowthRecord,
    'growth_records_count': growthRecords.length,
    'vaccination_status': {
      'completed': completedVaccines,
      'total': totalVaccines,
      'completion_rate':
          totalVaccines > 0 ? (completedVaccines / totalVaccines * 100) : 0,
      'overdue': overdueVaccines,
    },
    'milestones': {
      'achieved': milestones.length,
      'recent': milestones.take(5).toList(),
    },
    'latest_assessment': latestAssessment,
    'generated_date': DateTime.now(),
  };
}

// 导出宝宝数据
Future<String> exportBabyData(int babyId) async {
  final babyInfo = await getBabyInfo(babyId);
  if (babyInfo == null) {
    throw Exception('宝宝信息不存在');
  }

  // 收集所有相关数据
  final growthRecords = await getGrowthRecords(babyId);
  final vaccineRecords = await getVaccineRecords(babyId);
  final feedingRecords = await getFeedingRecords(babyId);
  final sleepRecords = await getSleepRecords(babyId);
  final milestones = await getGrowthMilestones(babyId);

  final data = {
    'baby_info': babyInfo.toMap(),
    'growth_records': growthRecords,
    'vaccine_records': vaccineRecords.map((record) => record.toMap()).toList(),
    'feeding_records': feedingRecords.map((record) => record.toMap()).toList(),
    'sleep_records': sleepRecords.map((record) => record.toMap()).toList(),
    // 'diaper_records': await getDiaperRecords(babyId), // 方法已注释
    'milestones': milestones.map((record) => record.toMap()).toList(),
    // 'assessments': await getDevelopmentAssessments(babyId), // 方法已注释
    'export_date': DateTime.now().toIso8601String(),
  };

  // 转换为JSON字符串
  final jsonData = jsonEncode(data);

  // 保存到文件
  final directory = await getApplicationDocumentsDirectory();
  final fileName =
      'baby_${babyId}_data_${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())}.json';
  final filePath = '${directory.path}/$fileName';

  File(filePath).writeAsStringSync(jsonData);

  return filePath;
}

// 私有辅助方法

// 分析生长趋势 - 为addGrowthRecord方法调用添加
// 分析生长趋势 - 为addGrowthRecord方法调用添加
Future<void> _analyzeGrowthTrend(int babyId) async {
  // 此方法暂时为空实现，仅用于修复编译错误
  // 实际实现可参考_evaluateGrowthTrend方法
  final records = await getGrowthRecords(babyId);
  if (records.length >= 3) {
    // 可以在这里添加实际的趋势分析逻辑
    debugPrint('Analyzing growth trend for baby $babyId');
  }
}

// 评估生长趋势
String _evaluateGrowthTrend(List<GrowthRecord> records) {
  if (records.length < 3) return '数据不足，无法评估趋势';

  // 按日期排序
  records.sort((a, b) => a.date.compareTo(b.date));

  // 计算体重和身高的线性回归斜率
  final weightSlope = _calculateLinearSlope(
      records.map((r) => r.date.millisecondsSinceEpoch.toDouble()).toList(),
      records.map((r) => r.weight).toList());

  final heightSlope = _calculateLinearSlope(
      records.map((r) => r.date.millisecondsSinceEpoch.toDouble()).toList(),
      records.map((r) => r.height).toList());

  // 根据斜率评估趋势
  if (weightSlope > 0.0000001 && heightSlope > 0.000001) {
    return '生长良好，体重和身高均有稳定增长';
  } else if (weightSlope > 0.0000001 && heightSlope <= 0.000001) {
    return '体重增长正常，但身高增长较慢';
  } else if (weightSlope <= 0.0000001 && heightSlope > 0.000001) {
    return '身高增长正常，但体重增长较慢';
  } else {
    return '体重和身高增长较慢，建议咨询医生';
  }
}

// 计算线性回归斜率
double _calculateLinearSlope(List<double> x, List<double> y) {
  final n = x.length;
  double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;

  for (int i = 0; i < n; i++) {
    sumX += x[i];
    sumY += y[i];
    sumXY += x[i] * y[i];
    sumX2 += x[i] * x[i];
  }

  final slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
  return slope;
}



// 加载默认的疫苗接种计划
Future<void> _loadDefaultVaccineSchedule(
    int babyId, String gender, DateTime dateOfBirth) async {
  // 检查是否已有疫苗计划 - 使用queryRows检查
  final existingSchedule = await getVaccineRecords(babyId);
  if (existingSchedule.isNotEmpty) return;

  // 默认疫苗计划
  final defaultSchedule = [
    {
      'vaccineName': '乙肝疫苗',
      'vaccineType': '基础免疫',
      'recommendedAge': '出生时',
      'dueDate': dateOfBirth,
      'description': '预防乙型肝炎',
    },
    {
      'vaccineName': '卡介苗',
      'vaccineType': '基础免疫',
      'recommendedAge': '出生后24小时内',
      'dueDate': dateOfBirth.add(Duration(days: 1)),
      'description': '预防结核病',
    },
    {
      'vaccineName': '乙肝疫苗(第2针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '1月龄',
      'dueDate': dateOfBirth.add(Duration(days: 30)),
      'description': '预防乙型肝炎',
    },
    {
      'vaccineName': '脊灰疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '2月龄',
      'dueDate': dateOfBirth.add(Duration(days: 60)),
      'description': '预防脊髓灰质炎',
    },
    {
      'vaccineName': '百白破疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '3月龄',
      'dueDate': dateOfBirth.add(Duration(days: 90)),
      'description': '预防百日咳、白喉、破伤风',
    },
    {
      'vaccineName': '脊灰疫苗(第2针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '4月龄',
      'dueDate': dateOfBirth.add(Duration(days: 120)),
      'description': '预防脊髓灰质炎',
    },
    {
      'vaccineName': '百白破疫苗(第2针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '4月龄',
      'dueDate': dateOfBirth.add(Duration(days: 120)),
      'description': '预防百日咳、白喉、破伤风',
    },
    {
      'vaccineName': '百白破疫苗(第3针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '5月龄',
      'dueDate': dateOfBirth.add(Duration(days: 150)),
      'description': '预防百日咳、白喉、破伤风',
    },
    {
      'vaccineName': '乙肝疫苗(第3针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '6月龄',
      'dueDate': dateOfBirth.add(Duration(days: 180)),
      'description': '预防乙型肝炎',
    },
    {
      'vaccineName': 'A群流脑疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '6月龄',
      'dueDate': dateOfBirth.add(Duration(days: 180)),
      'description': '预防A群脑膜炎球菌引起的流行性脑脊髓膜炎',
    },
    {
      'vaccineName': 'A群流脑疫苗(第2针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '9月龄',
      'dueDate': dateOfBirth.add(Duration(days: 270)),
      'description': '预防A群脑膜炎球菌引起的流行性脑脊髓膜炎',
    },
    {
      'vaccineName': '乙脑减毒活疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '8月龄',
      'dueDate': dateOfBirth.add(Duration(days: 240)),
      'description': '预防乙型脑炎',
    },
    {
      'vaccineName': '麻腮风疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '8月龄',
      'dueDate': dateOfBirth.add(Duration(days: 240)),
      'description': '预防麻疹、腮腺炎、风疹',
    },
    {
      'vaccineName': '甲肝减毒活疫苗(第1针)',
      'vaccineType': '基础免疫',
      'recommendedAge': '18月龄',
      'dueDate': dateOfBirth.add(Duration(days: 540)),
      'description': '预防甲型肝炎',
    },
  ];

  // 插入默认计划
  for (var scheduleItem in defaultSchedule) {
    // 暂时注释掉，因为tableVaccineSchedule不存在
    // final vaccineSchedule = VaccineSchedule(
    //   babyId: babyId,
    //   vaccineName: scheduleItem['vaccineName']?.toString() ?? '',
    //   vaccineType: scheduleItem['vaccineType']?.toString() ?? '',
    //   recommendedAge: scheduleItem['recommendedAge']?.toString() ?? '',
    //   dueDate: scheduleItem['dueDate'] as DateTime,
    //   description: scheduleItem['description']?.toString() ?? '',
    //   importance: '这是国家免疫规划疫苗，建议按计划接种',
    //   sideEffects: '接种后可能出现注射部位红肿、疼痛，一般2-3天自行缓解',
    // );
    // await dbHelper.insert('vaccine_schedule', vaccineSchedule.toMap());
    debugPrint('疫苗计划: ${scheduleItem['vaccineName']}');
  }
  }

  // 加载默认的早教方案
  Future<void> _loadDefaultEarlyEducationPlans(int babyId) async {
  // 检查是否已有早教方案 - 暂时跳过检查
  // final existingCount = await dbHelper.queryRows('early_education_plans', where: {'baby_id': babyIdValue}).length;
  // if (existingCount > 0) return;

  // 默认早教方案
  final defaultPlans = [
    // 0-3个月
    EarlyEducationPlan(
      babyId: babyId,
      title: '视觉追踪训练',
      description: '帮助宝宝发展视觉追踪能力',
      targetAgeRange: '0-3m',
      category: 'cognitive',
      activityType: '感官刺激',
      instructions:
          '1. 在距离宝宝眼睛20-30厘米处悬挂一个色彩鲜艳的玩具\n2. 缓慢地从一侧移动到另一侧\n3. 观察宝宝的眼睛是否跟随移动\n4. 每天进行2-3次，每次约5分钟',
      materialsNeeded: '彩色玩具、悬挂装置',
      benefits: '增强视觉注意力，促进眼肌发育，建立空间感知',
      tips: '确保光线充足，但避免强光直射宝宝眼睛',
      difficultyLevel: 'easy',
      durationMinutes: 5,
    ),
    EarlyEducationPlan(
      babyId: babyId,
      title: '触觉刺激游戏',
      description: '通过不同质地的物品刺激宝宝触觉发育',
      targetAgeRange: '0-3m',
      category: 'motor_skills',
      activityType: '感官刺激',
      instructions:
          '1. 准备各种质地的材料（如毛绒玩具、丝绸、毛巾等）\n2. 轻轻触摸宝宝的手掌、脚掌和脸部\n3. 观察宝宝的反应\n4. 每天进行1-2次，每次约5分钟',
      materialsNeeded: '各种质地的布料和玩具',
      benefits: '促进触觉感知发育，增强感官系统敏感性',
      tips: '确保材料干净、柔软，温度适宜',
      difficultyLevel: 'easy',
      durationMinutes: 5,
    ),
    // 4-6个月
    EarlyEducationPlan(
      babyId: babyId,
      title: '翻身练习',
      description: '帮助宝宝学习翻身动作',
      targetAgeRange: '4-6m',
      category: 'motor_skills',
      activityType: '运动训练',
      instructions:
          '1. 将宝宝放在平坦的床上或垫子上\n2. 用玩具吸引宝宝的注意力\n3. 在一侧轻轻推宝宝的臀部，帮助翻身\n4. 每天练习3-4次，每次约10分钟',
      materialsNeeded: '柔软的垫子、有趣的玩具',
      benefits: '增强颈部、背部和腹部肌肉力量，促进大运动发育',
      tips: '确保环境安全，避免宝宝受伤',
      difficultyLevel: 'medium',
      durationMinutes: 10,
    ),
    // 7-12个月
    EarlyEducationPlan(
      babyId: babyId,
      title: '爬行隧道游戏',
      description: '通过隧道游戏鼓励宝宝爬行',
      targetAgeRange: '7-12m',
      category: 'motor_skills',
      activityType: '运动训练',
      instructions:
          '1. 准备一个儿童爬行隧道或用纸箱制作简易隧道\n2. 在隧道另一端放置宝宝喜欢的玩具\n3. 鼓励宝宝爬过隧道取玩具\n4. 每天进行2-3次，每次约15分钟',
      materialsNeeded: '爬行隧道或纸箱、吸引宝宝的玩具',
      benefits: '增强全身肌肉力量，高平衡能力和空间感知',
      tips: '可以在隧道内放置一些柔软的障碍物增加趣味性',
      difficultyLevel: 'medium',
      durationMinutes: 15,
    ),
    // 1-2岁
    EarlyEducationPlan(
      babyId: babyId,
      title: '积木搭建游戏',
      description: '通过搭建积木培养宝宝的创造力和手眼协调能力',
      targetAgeRange: '1-2y',
      category: 'cognitive',
      activityType: '创意游戏',
      instructions:
          '1. 提供适合宝宝年龄的大颗粒积木\n2. 示范如何搭建简单的结构\n3. 鼓励宝宝自己尝试搭建\n4. 可以设定主题，如盖房子、建桥等\n5. 每天进行1-2次，每次约15-20分钟',
      materialsNeeded: '大颗粒积木',
      benefits: '发展精细运动技能，培养空间想象力和解决问题的能力',
      tips: '不要急于纠正宝宝的搭建方式，鼓励自由发挥',
      difficultyLevel: 'medium',
      durationMinutes: 20,
    ),
    // 2-3岁
    EarlyEducationPlan(
      babyId: babyId,
      title: '角色扮演游戏',
      description: '通过角色扮演促进宝宝的社交和语言发展',
      targetAgeRange: '2-3y',
      category: 'social_emotional',
      activityType: '角色扮演',
      instructions:
          '1. 提供简单的角色扮演服装和道具\n2. 选择简单的场景，如超市购物、医生看病等\n3. 和宝宝一起进行角色扮演\n4. 鼓励宝宝表达自己的想法和感受\n5. 每天进行1次，每次约20-30分钟',
      materialsNeeded: '角色扮演服装、玩具道具',
      benefits: '提高语言表达能力，发展社交技能，增强想象力',
      tips: '尊重宝宝的创意，不要过多干预宝宝的表演',
      difficultyLevel: 'medium',
      durationMinutes: 30,
    ),
  ];

  // 插入默认方案
  for (var plan in defaultPlans) {
    // 暂时注释掉，因为数据库表可能不存在
    // await _dbHelper.insertEarlyEducationPlan(plan.toMap());
    debugPrint('早教方案: ${plan.title}');
  }
  }

  // 创建疫苗接种提醒
  Future<void> _createVaccineReminder(int babyIdValue, DateTime dueDate,
      String vaccineNameValue, String? doseValue) async {
  // 计算提醒时间（提前1天和3天）
  final reminders = [
    dueDate.subtract(Duration(days: 3)),
    dueDate.subtract(Duration(days: 1)),
  ];

  for (var reminderDate in reminders) {
    if (reminderDate.isAfter(DateTime.now())) {
      // 暂时注释掉，因为tableReminders不存在且_dbHelper未定义
      /*await dbHelper.insert('reminders', {
          'user_id': babyIdValue, // 暂时使用babyIdValue作为userId
          'title': '疫苗接种提醒',
          'description': '您的宝宝需要在${DateFormat('yyyy-MM-dd').format(dueDate)}接种$vaccineNameValue${doseValue != null ? '($doseValue)' : ''}。',
          'reminder_date': reminderDate.toIso8601String(),
          'type': 'vaccine',
          'created_at': DateTime.now().toIso8601String(),
        });*/
    }
  }
  }


}
